package org.skydiveapplibrary.ui;

import org.skydiveapplibrary.R;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.TextView;

public class NumberDialog extends AlertDialog
{
	// listener definition
	public interface OnNumberSetListener
	{
		void onNumberSet(NumberDialog dialog, int number);
	}
	
	// listeners
	private OnNumberSetListener onNumberSetListener;
	private OnClickListener okClickListener = new OnClickListener()
	{
		@Override
		public void onClick(DialogInterface arg0, int arg1)
		{
			handleOKClick();
		}
	};
	private OnClickListener cancelClickListener = new OnClickListener()
	{
		@Override
		public void onClick(DialogInterface arg0, int arg1)
		{
			dismiss();
		}
	};
	
	// data
	private int mNumber = 0;
	
	public NumberDialog(
			Context context,
			int titlaResId,
			int number,
			OnNumberSetListener onNumberSetListener)
	{
		super(context);
		
		this.onNumberSetListener = onNumberSetListener;
		
		// get view
		View view = View.inflate(context, R.layout.number_dialog, null);
		
		// init view
		setView(view, 10, 10, 10, 10);
		setButton(
				context.getString(android.R.string.ok),
				okClickListener);
		setButton2(
				context.getString(android.R.string.cancel),
				cancelClickListener);
		setTitle(titlaResId);
		
		// init data
		mNumber = number;
	}
	
	public void show()
	{
		super.show();
		// init fields
		TextView numberField = (TextView)findViewById(R.id.NumberField);
		numberField.setText(FormatUtility.toNumericString(mNumber));
	}
	
	private void handleOKClick()
	{
		// get new number
		TextView numberField = (TextView)findViewById(R.id.NumberField);

		// get hours
		String numberString = numberField.getText() == null ? null : numberField.getText().toString();
		int number = FormatUtility.toInteger(numberString, 0);
		
		if (onNumberSetListener != null)
		{
			onNumberSetListener.onNumberSet(this, number);
		}
		
		// dismiss dialog
		dismiss();
	}
}
